/*
 * Copyright (c) 2014 - 2016. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.category;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.renderscript.Int2;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.activity.home.wrap.CategoryHolder;
import cn.com.dhc.danlu.util.ACache;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.SerializeCache;
import cn.com.dhc.danlu.widget.CustomerSpinner;
import cn.com.dhc.danlu.widget.GoodsGridView;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.dhc.mibd.eufw.widget.android.ptr.PullToRefreshGridView;
import cn.com.hd.mall.web.common.Tuple;
import cn.com.hd.mall.web.webservices.entity.request.merch.MerchListRequest;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * 分类画面
 *
 * @author MuWei
 * @version 1.00 2015/02/05 新建
 */

public class CategoryActivity extends BaseActivity implements AnimatorListener {
    /**
     * 初始页数
     */
    private static final int DEFAULT_PAGE = 1;
    /**
     * 低价传递参数
     */
    private static final String LOW_PRICE = "0";
    /**
     * 高价传递参数
     */
    private static final String HIGH_PRICE = "1";
    /**
     * 按名字排序 0按名字 1 按价格
     */
    private static final String NAME_SORT = "0";
    private static final String PRICE_SORT = "1";
    /**
     * 按销量排序标识
     */
    boolean isPrice = false;
    /**
     * 商品平铺列表
     */
    private GoodsGridView goodsGridView;
    /**
     * 下拉刷新平铺列表
     */
    private PullToRefreshGridView grdGoods;
    /**
     * 顶部
     */
    private LinearLayout llTopBar;
    /**
     * 显示标签布局
     */
    private LinearLayout llytShowTab;
    /**
     * 价格按钮
     */
    private LinearLayout llytPriceSearch;
    /**
     * 销量按钮
     */
    private LinearLayout llytCountSearch;
    /**
     * 筛选按钮
     */
    private LinearLayout llytTxtFilter;
    /**
     * 综合文本
     */
    private TextView llytCountSearchTxt;
    /**
     * 价格文本
     */
    private TextView llytPriceSearchTxt;
    /**
     * 没商品时显示信息
     */
    private LinearLayout llytNoData;
    /**
     * 价格图标
     */
    private ImageView imgPriceSearch;
    /**
     * 销量图标
     */
    private ImageView imgCountSearch;
    /**
     * 筛选
     */
    private TextView txtFilter;
    /**
     * 显示行数
     */
    private int rows = CommonConst.LIST_NUM;
    /**
     * 页数
     */
    private int page = 1;
    /**
     * 请求参数类
     */
    private MerchListRequest goodsform = new MerchListRequest ();
    /**
     * 商品分类监听类
     */
    private CategoryListener categoryListener;
    /**
     * 传入品牌list
     */
    private ArrayList<String> list;
    /**
     * 品牌下拉
     */
    private CustomerSpinner btnSpinner;

    private CategoryHolder mCategoryHolder;
    /**
     * 下拉父窗口
     */
    private LinearLayout llytSpinner;
    /**
     * 综合下的view
     */
    private View viewCount;
    /**
     * 价格下的view
     */
    private View viewPrice;
    /**
     * 筛选下的view
     */
    private View viewFilter;
    /**
     * 搜索返回的文字
     */
    private TextView txtSearch;
    private ACache aCache;

    @Override
    protected void onNewIntent (Intent intent) {
        super.onNewIntent (intent);
        final String code = intent.getStringExtra ("code");
        final String brandId = intent.getStringExtra ("brandId");
        final String des = intent.getStringExtra ("des");
        if (!TextUtils.isEmpty (code) && !TextUtils.isEmpty (des)) {
            btnSpinner.postDelayed (new Runnable () {
                @Override
                public void run () {
                    btnSpinner.forcedToScreen (code, brandId, des);
                    btnSpinner.setPopSection (getIndexByDes (des));
                }
            }, 200);
        } else {
            //搜索
            boolean isFromHomeSearch = intent.getBooleanExtra (CommonConst.IntentKey.SEARCH_RANGE_KEY, false);
            if (isFromHomeSearch) {
                btnSpinner.setText (R.string.classify);
                searchAction (intent, false);
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent (MotionEvent ev) {
        CommonUtils.hideSoftInputForce (this);
        return super.dispatchTouchEvent (ev);
    }

    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
        super.onActivityResult (requestCode, resultCode, data);
        // 实例化一个Bundle对象接收回传的数据
        Bundle bundle;
        if (requestCode == 0 && resultCode == RESULT_OK) { // 筛选页面的返回
            bundle = data.getExtras ();
            // 实例化分类请求对象并接收
            MerchListRequest form;
            // bundle中传回的请求数据对象
            form = (MerchListRequest) bundle.getSerializable ("form");
            txtFilter.setTextColor (Color.RED);
            // 清除原有请求实例goodsform中的参数
            clearGoodsForm ();
            // 设置返回数据页数为默认
            goodsform.setPage (DEFAULT_PAGE);
            // 设置返回行
            goodsform.setRows (rows);
            // btnSpinner.setBrand(form.getBrand());
            // 设置茶类ID
            if (form.getMerchCategoryCode () != null && !form.getMerchCategoryCode ().equals ("null")) {
                goodsform.setMerchCategoryCode (form.getMerchCategoryCode ());
            } else {
                goodsform.setMerchCategoryCode (btnSpinner.getMerchandiseType ());
            }
            Int2 indexs = SerializeCache.getInstance ().getCategoryIndexs ();
            String fromTag = agent.getFromTag ();
            String firstClassifyName = btnSpinner.getText ().toString ();
            //是否新增加的分类  LLQ
            boolean isNewClassify = !(firstClassifyName.equals (getString (R.string.category_white_wine)) || firstClassifyName.equals (getString (R.string.category_beer)) || firstClassifyName.equals (getString (R.string.category_red_wine)) || firstClassifyName.equals (getString (R.string.category_foreign_wine)));
            if (fromTag.equals ("CategoryHolder")) {  // 从首页"分类"进入
                if (agent.getCategory (indexs.x) == null) {
                    return;
                }
                //是新分类，且未筛选未选全部商品
                if (isNewClassify && indexs.y != -1) {
                    if (null == agent.getCategory (indexs.x, indexs.y)) {
                        return;
                    }
                    String code = agent.getCategory (indexs.x, indexs.y).getCode ();  //所选二级分类码
                    goodsform.setMerchCategoryCode (code);
                } else if (!isNewClassify) {
                    String code = agent.getCategory (indexs.x).getCode ();
                    goodsform.setMerchCategoryCode (code);
                }
            }
            // 清空 为空的属性
            if (form.getMerchPropertyValueCodeList () != null) {
                for (int i = 0; i < form.getMerchPropertyValueCodeList ().size (); i++) {
                    if (form.getMerchPropertyValueCodeList ().get (i) == null) {
                        form.getMerchPropertyValueCodeList ().remove (i);
                    }
                }
            }
            // 设置属性
            goodsform.setMerchPropertyValueCodeList (form.getMerchPropertyValueCodeList ());
            // 设置品牌码
            goodsform.setMerchBrandId (form.getMerchBrandId ());
            // 设置高价
            if (!TextUtils.isEmpty (form.getHighPrice ())) {
                long hp = Long.parseLong (form.getHighPrice ());
                String hPrice = CommonUtils.yuanToFen (BigDecimal.valueOf (hp)).toString ();
                goodsform.setHighPrice (hPrice);
            } else {
                goodsform.setHighPrice (null);
            }

            // 设置低价
            if (!TextUtils.isEmpty (form.getLowPrice ())) {
                long lp = Long.parseLong (form.getLowPrice ());
                String lPrice = CommonUtils.yuanToFen (BigDecimal.valueOf (lp)).toString ();
                goodsform.setLowPrice (lPrice);
            } else {
                goodsform.setLowPrice (null);
            }
            // 设置名字排序
            goodsform.setSortField (NAME_SORT);
            // 降序
            goodsform.setSortType (HIGH_PRICE);
            goodsGridView.getCateList (true, goodsform);   // 调用更新列表方法
            //            aCache.getAsString ("isClick").equals ("0");
        } else if (requestCode == 1 && resultCode == RESULT_OK) { // 搜索的返回
            //
            searchAction (data, false);
        }
    }

    protected int getIndexByDes (String des) {
        int index = 0;
        for (int i = 0; i < list.size (); i++) {
            if (list.get (i).equals (des)) {
                index = i;
                break;
            }
        }
        return index;
    }

    /**
     * 搜索的回调操作
     *
     * @param data
     *         搜索页面的返回intent
     * @param isSearchByLastCode
     *         是否通过上次的码搜索
     */
    public void searchAction (Intent data, boolean isSearchByLastCode) {
        clearGoodsForm ();
        // 设置默认综合排序
        setDefaultSort ();
        // 设置搜索字
        String search = data.getStringExtra (CommonConst.IntentKey.KEY_WORD);
        if (!TextUtils.isEmpty (search) && search.replaceAll (" ", "").length () > 0) {
            txtSearch.setText (search);
            goodsform.setMerchName (search.replaceAll (" ", ""));
        } else {
            txtSearch.setText (getResources ().getString (R.string.good_info_search_btnok));
            goodsform.setMerchName (null);
        }
        // 清除原有请求实例goodsform中的参数
        //        if (isSearchByLastCode) {
        goodsform.setMerchCategoryCode (btnSpinner.getMerchandiseType ());
        //        } else {
        //            goodsform.setMerchCategoryCode(null);
        //        }
        // 设置返回页数
        goodsform.setPage (page);
        // 设置返回行数
        goodsform.setRows (rows);
        goodsform.setSortField (NAME_SORT);
        goodsform.setSortType (LOW_PRICE);
        goodsGridView.getCateList (true, goodsform);
    }

    /**
     * 清除一下请求参数类中参数
     */
    private void clearGoodsForm () {
        // 清除品牌码
        goodsform.setMerchBrandId (null);
        goodsform.setMerchPropertyValueCodeList (null);
        // 清除高价
        goodsform.setHighPrice (null);
        // 清除低价
        goodsform.setLowPrice (null);
        // 清除商品名称
        goodsform.setMerchName (null);
    }

    /**
     * 清空后设置默认综合排序
     */
    private void setDefaultSort () {
        // 默认综合排序
        imgCountSearch.setVisibility (View.VISIBLE);
        imgPriceSearch.setVisibility (View.INVISIBLE);
        llytPriceSearchTxt.setTextColor (Color.BLACK);
        llytCountSearchTxt.setTextColor (Color.RED);
        txtFilter.setTextColor (Color.BLACK);
        // 综合tab下的红色线显示
        viewPrice.setVisibility (View.INVISIBLE);
        viewCount.setVisibility (View.VISIBLE);
        viewFilter.setVisibility (View.INVISIBLE);
        // 设置排序图片
        //        imgCountSearch.setBackgroundDrawable(delegate.getContext().getResources().getDrawable(R.drawable.category_sort_up));
        imgCountSearch.setBackgroundDrawable (getResources ().getDrawable (R.drawable.category_sort_up));
        aCache.put ("count", "1");
    }

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_category);

        initViews ();
        setViews ();
        setListener ();
        handleEntrust ();
    }

    private void initViews () {
        grdGoods = (PullToRefreshGridView) findViewById (R.id.grdGoods);
        llytShowTab = (LinearLayout) findViewById (R.id.llytShowTab);
        llytNoData = (LinearLayout) findViewById (R.id.llytNoData);
        btnSpinner = (CustomerSpinner) findViewById (R.id.btnSpinner);
        llytSpinner = (LinearLayout) findViewById (R.id.llytSpinner);
        txtSearch = (TextView) findViewById (R.id.txtSearch);
        llTopBar = (LinearLayout) findViewById (R.id.ll_topbar);
        llytPriceSearch = (LinearLayout) findViewById (R.id.llytPriceSearch);
        llytCountSearch = (LinearLayout) findViewById (R.id.llytCountSearch);
        llytTxtFilter = (LinearLayout) findViewById (R.id.llytTxtFilter);
        llytCountSearchTxt = (TextView) findViewById (R.id.llytCountSearch_txt);
        llytPriceSearchTxt = (TextView) findViewById (R.id.llytPriceSearch_txt);
        imgPriceSearch = (ImageView) findViewById (R.id.imgPriceSearch);
        imgCountSearch = (ImageView) findViewById (R.id.imgCountSearch);
        txtFilter = (TextView) findViewById (R.id.txtFilter);
        viewCount = findViewById (R.id.viewCount);
        viewPrice = findViewById (R.id.viewPrice);
        viewFilter = findViewById (R.id.viewFilter);
    }

    @Override
    protected String getActivityTitle () {
        return null;
    }

    /**
     * 画面初始化
     */
    private void setViews () {
        // 清除缓存
        CommonUtils.clearAllCgrPrtBrd (getApplicationContext ());
        // 默认1没点击
        aCache = ACache.get (getApplicationContext ());
        aCache.put ("isClick", "1");
        aCache.put ("count", "1"); //wtf ? web是
        // 默认茶类1为改变
        aCache.put ("teaSeedChange", "1");
        // 商品平铺列表初始化
        goodsGridView = new GoodsGridView (CategoryActivity.this, grdGoods, llytNoData);
        // 商品信息平铺列表初始化
        goodsGridView.init ();
        // 默认白酒
        Intent intent = getIntent ();
        boolean isGlobalSearch = intent.getBooleanExtra (CommonConst.IntentKey.SEARCH_RANGE_KEY, false);
        if (!TextUtils.isEmpty (intent.getStringExtra ("code")) && !isGlobalSearch) {
            goodsform.setMerchCategoryCode (intent.getStringExtra ("code"));
            if (!TextUtils.isEmpty (intent.getStringExtra ("brandId"))) {
                goodsform.setMerchBrandId (intent.getStringExtra ("brandId"));
            }

        }
        // 设置返回页数
        goodsform.setPage (page);
        // 设置返回行数
        goodsform.setRows (rows);
        goodsform.setSortType (LOW_PRICE);
        // 设置按什么方式排序
        goodsform.setSortField (NAME_SORT);
        // 设置token
        goodsform.setToken (agent.getToken ());
        String extra = getIntent ().getStringExtra (CommonConst.IntentKey.KEY_WORD);
        //如果不为空 说明是从首页传入搜索参数过来 并且当前的分类activity之前还未实例化  此时控制当前不去加载 加载业务逻辑控制到handleEntrust 中
        if (TextUtils.isEmpty (extra)) {
            // 调用更新列表方法
            goodsGridView.getCateList (true, goodsform);
        }
        // 设置平铺列表点击事件
        categoryListener = new CategoryListener ();
        // 设置spinner
        setSpinner ();
        // 默认综合排序为红色字体
        llytCountSearchTxt.setTextColor (Color.RED);
        imgCountSearch.setBackgroundDrawable (getResources ().getDrawable (R.drawable.category_sort_up));
        mCategoryHolder = new CategoryHolder (this);
    }

    /**
     * 设置搜索按钮监听
     */
    private void setListener () {
        // 价格按钮点击事件监听
        llytPriceSearch.setOnClickListener (categoryListener);
        // 筛选按钮监听
        llytTxtFilter.setOnClickListener (categoryListener);
        // 销量按钮点击事件监听
        llytCountSearch.setOnClickListener (categoryListener);
        // 标签布局点击事件监听
        llytShowTab.setOnClickListener (new OnClickListener () {

            @Override
            public void onClick (View v) {
                // 新建意图对象
                Intent intent = new Intent (CategoryActivity.this, GoodInfoSearchActivity.class);// GoodInfoSearchActivity
                intent.putExtra ("search", txtSearch.getText ().toString ());
                // 跳转到搜索界面
                startActivityForResult (intent, 1);
            }
        });
    }

    private void handleEntrust () {
        String extra = getIntent ().getStringExtra (CommonConst.IntentKey.KEY_WORD);
        if (!TextUtils.isEmpty (extra)) {
            searchAction (getIntent (), false);
        }
    }


    /**
     * 设置spinner
     */
    private void setSpinner () {
        list = new ArrayList<> ();
        list.add (getString (R.string.category_white_wine));
        list.add (getString (R.string.category_red_wine));
        list.add (getString (R.string.category_tea));
        list.add (getString (R.string.category_foreign_wine));
        list.add (getString (R.string.category_beer));
        list.add (getString (R.string.category_other_wine));
        btnSpinner.setList (list);
        Intent intent = getIntent ();
        String des = intent.getStringExtra ("des");
        boolean isGlobalSearch = intent.getBooleanExtra (CommonConst.IntentKey.SEARCH_RANGE_KEY, false);
        if (!TextUtils.isEmpty (des) && !isGlobalSearch) {
            btnSpinner.setText (des);
        } else {
            //默认分类  之前是白酒
            btnSpinner.setText (getString (R.string.classify));
        }
        btnSpinner.setGoodsGridView (goodsGridView);
        btnSpinner.setLinearLayout (llytSpinner);
        btnSpinner.setSearchTextView (txtSearch);
        btnSpinner.setImgCountSearch (imgCountSearch);
        btnSpinner.setImgPriceSearch (imgPriceSearch);
        btnSpinner.setLlytCountSearch_txt (llytCountSearchTxt);
        btnSpinner.setLlytPriceSearch_txt (llytPriceSearchTxt);
        btnSpinner.setTxtFilter (txtFilter);
        btnSpinner.setViewPrice (viewPrice);
        btnSpinner.setViewCount (viewCount);
        btnSpinner.setViewFilter (viewFilter);
        btnSpinner.setPopSection (getIndexByDes (des));
        btnSpinner.setOnClickListener (new OnClickListener () {
            @Override
            public void onClick (View view) {
                mCategoryHolder.toggleCategoryPanel (llTopBar);
            }
        });
    }

    @Override
    public void onAnimationStart (Animator arg0) {
    }

    @Override
    public void onAnimationEnd (Animator arg0) {
    }

    @Override
    public void onAnimationCancel (Animator arg0) {
    }

    @Override
    public void onAnimationRepeat (Animator arg0) {
    }

    @Override
    protected void onResume () {
        super.onResume ();
        if (mCategoryHolder.isShowing ()) {
            mCategoryHolder.hide ();
        }
    }

    /**
     * 列表点击事件监听类
     */
    private class CategoryListener implements OnClickListener {

        @Override
        public void onClick (View v) {
            // 饮料、粮油、副食和其它，并且选择了全部XX商品（XX饮料、粮油、副食和其它，并且选择了全部XX商品（XX 需要将二级分类名称传过去
            Int2 indexs = SerializeCache.getInstance ().getCategoryIndexs ();
            // 获取跳转源头标志--SelectTypeHeader，首页点击进入；CategoryHolder，点击“分类”进入
            String fromTag = agent.getFromTag ();
            String merchName = txtSearch.getText ().toString ().trim (); // 获取搜索栏内容
            // 获取品牌码/名的缓存体
            Tuple<String, String> tupleBrand = (Tuple<String, String>) aCache.getAsObject (CommonConst.ACacheComstants.BRAND);
            String tuplePrice = aCache.getAsString (CommonConst.ACacheComstants.PRICE);
            CommonUtils.CachingArrayList tupleProperty = (CommonUtils.CachingArrayList) aCache.getAsObject (CommonConst.ACacheComstants.PROPERTY);
            switch (v.getId ()) {
                case R.id.llytPriceSearch:  //价格排序
                    // 显示价格图片
                    llytPriceSearchTxt.setTextColor (Color.RED);
                    llytCountSearchTxt.setTextColor (Color.BLACK); //综合
                    txtFilter.setTextColor (Color.BLACK);  //筛选
                    // 价格tab下的红色线显示
                    viewPrice.setVisibility (View.VISIBLE);
                    viewCount.setVisibility (View.INVISIBLE);
                    viewFilter.setVisibility (View.INVISIBLE);
                    imgCountSearch.setVisibility (View.INVISIBLE);
                    imgPriceSearch.setVisibility (View.VISIBLE);
                    // 按高价排序
                    String isClick = aCache.getAsString ("isClick");
                    if (isPrice) {
                        // 图标设置为向下
                        imgPriceSearch.setBackgroundDrawable (getResources ().getDrawable (R.drawable.category_sort_fall));
                        // 设置品类码
                        if (!TextUtils.isEmpty (isClick) && isClick.equals ("0")) {
                            clearGoodsForm ();
                            setMerchCategoryCode (tupleProperty, indexs, fromTag); // 设置品类码
                        }
                        setBrandId (tupleBrand, indexs, fromTag); // 设置品牌码
                        setMerchName (merchName); // 设置搜索栏商品名
                        setMerchPropertyValueCodeList (tupleProperty); //设置请求商品属性
                        setPriceInterval (tuplePrice); // 设置请求商品列表价格区间
                        // 设置价格排序
                        goodsform.setSortField (PRICE_SORT);
                        goodsform.setSortType (HIGH_PRICE); // 设置为降序
                        // 设置返回数据页数为默认
                        goodsform.setPage (DEFAULT_PAGE);
                        // 设置返回行数
                        goodsform.setRows (rows);
                        // 调用更新列表方法
                        goodsGridView.getCateList (true, goodsform);
                        // 改为按低价
                        isPrice = false;
                    } else {
                        // 获取品类码
                        if (!TextUtils.isEmpty (isClick) && isClick.equals ("0")) {
                            clearGoodsForm ();
                            setMerchCategoryCode (tupleProperty, indexs, fromTag); // 设置品类码
                        }
                        setBrandId (tupleBrand, indexs, fromTag); // 设置品牌码
                        setMerchName (merchName); // 设置搜索栏商品名
                        setMerchPropertyValueCodeList (tupleProperty); //设置请求商品属性
                        setPriceInterval (tuplePrice); // 设置请求商品列表价格区间
                        // 设置价格排序
                        goodsform.setSortField (PRICE_SORT);
                        goodsform.setSortType (LOW_PRICE); // 设置为升序
                        // 设置返回数据页数为默认
                        goodsform.setPage (DEFAULT_PAGE);
                        // 设置返回行数
                        goodsform.setRows (rows);
                        // 设置价格排序图标
                        imgPriceSearch.setBackgroundDrawable (getResources ().getDrawable (R.drawable.category_sort_up));
                        // 调用更新列表方法
                        goodsGridView.getCateList (true, goodsform);
                        // 改为按高价
                        isPrice = true;
                    }
                    break;

                case R.id.llytCountSearch:  //综合排序
                    // 显示综合图片
                    imgCountSearch.setVisibility (View.VISIBLE);
                    imgPriceSearch.setVisibility (View.INVISIBLE);
                    llytPriceSearchTxt.setTextColor (Color.BLACK);
                    llytCountSearchTxt.setTextColor (Color.RED);
                    txtFilter.setTextColor (Color.BLACK);
                    // 综合tab下的红色线显示
                    viewPrice.setVisibility (View.INVISIBLE);
                    viewCount.setVisibility (View.VISIBLE);
                    viewFilter.setVisibility (View.INVISIBLE);
                    if (aCache.getAsString ("count").equals ("1")) {
                        // 设置销量排序图标
                        imgCountSearch.setBackgroundDrawable (getResources ().getDrawable (R.drawable.category_sort_fall));
                        // 获取品类码
                        if (aCache.getAsString ("isClick").equals ("0")) {
                            clearGoodsForm ();
                            setMerchCategoryCode (tupleProperty, indexs, fromTag); // 设置品类码
                        }
                        setBrandId (tupleBrand, indexs, fromTag); // 设置品牌码
                        setMerchName (merchName); // 设置搜索栏商品名
                        setMerchPropertyValueCodeList (tupleProperty); //设置请求商品属性
                        setPriceInterval (tuplePrice); // 设置请求商品列表价格区间
                        // 设置名字排序
                        goodsform.setSortField (NAME_SORT);
                        goodsform.setSortType (HIGH_PRICE); // 设置为降序
                        // 设置返回数据页数为默认
                        goodsform.setPage (DEFAULT_PAGE);
                        // 设置返回行数
                        goodsform.setRows (rows);
                        aCache.put ("count", "0");
                        // 调用更新列表方法
                        goodsGridView.getCateList (true, goodsform); //中间这个参数暂时未用到
                    } else {
                        // 设置销量排序图标
                        imgCountSearch.setBackgroundDrawable (getResources ().getDrawable (R.drawable.category_sort_up));
                        if (aCache.getAsString ("isClick").equals ("0")) {
                            clearGoodsForm ();
                            setMerchCategoryCode (tupleProperty, indexs, fromTag); // 设置品类码
                        }
                        setBrandId (tupleBrand, indexs, fromTag); // 设置品牌码
                        setMerchName (merchName); // 设置搜索栏商品名
                        setMerchPropertyValueCodeList (tupleProperty); //设置请求商品属性
                        setPriceInterval (tuplePrice); // 设置请求商品列表价格区间
                        // 设置名字排序
                        goodsform.setSortField (NAME_SORT);
                        goodsform.setSortType (LOW_PRICE); // 设置为升序
                        // 设置返回数据页数为默认
                        goodsform.setPage (DEFAULT_PAGE);
                        // 设置返回行数
                        goodsform.setRows (rows);
                        // COUNT = false;
                        aCache.put ("count", "1");
                        // 调用更新列表方法
                        goodsGridView.getCateList (true, goodsform);
                    }
                    break;

                case R.id.llytTxtFilter:  //筛选
                    String string = btnSpinner.getText ().toString ();
                    if (TextUtils.isEmpty (string) || string.equals (getResources ().getString (R.string.classify))) {
                        new ViewDialog.Builder (CategoryActivity.this).setMessage ("请选择分类").setPositiveButton (R.string.btn_confirm, new DialogInterface.OnClickListener () {
                            @Override
                            public void onClick (DialogInterface dialog, int which) {
                                dialog.dismiss ();
                                mCategoryHolder.toggleCategoryPanel (llTopBar);
                            }
                        }).setNegativeButton (R.string.cancel, new DialogInterface.OnClickListener () {
                            @Override
                            public void onClick (DialogInterface dialog, int which) {
                                dialog.dismiss ();
                            }
                        }).create ().show ();
                        return;
                    }
                    // 筛选tab下的红色线显示
                    viewPrice.setVisibility (View.INVISIBLE);
                    viewCount.setVisibility (View.INVISIBLE);
                    viewFilter.setVisibility (View.VISIBLE);
                    imgCountSearch.setVisibility (View.INVISIBLE);
                    imgPriceSearch.setVisibility (View.INVISIBLE);
                    llytPriceSearchTxt.setTextColor (Color.BLACK);
                    llytCountSearchTxt.setTextColor (Color.BLACK);
                    Intent intent = new Intent ();
                    intent.setClass (CategoryActivity.this, CategoryFilterActivity.class);
                    intent.addFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    intent.putExtra ("secondaryIndex", indexs.y); //是否选择全部
                    if (fromTag.equals ("CategoryHolder")) {  // 首页点击"分类"进入
                        if (agent.getCategory (indexs.x) == null) {
                            return;
                        }
                        intent.putExtra ("firstClassify", agent.getCategory (indexs.x).getName ());  //一级分类名
                        intent.putExtra (CommonConst.IntentKey.BRAND_CODE, agent.getCategory (indexs.x).getCode ()); //一级分类码
                        if (indexs.y != -1) { // 未选择“分类”，全部xx商品
                            if (null == agent.getCategory (indexs.x, indexs.y)) {
                                return;
                            }
                            intent.putExtra (CommonConst.IntentKey.SECOND_CLASSIFY_CODE, agent.getCategory (indexs.x, indexs.y).getCode ()); //二级分类码
                        }
                    }
                    if (fromTag.equals ("SelectTypeHeader")) {  // 首页点击进入
                        String firstClassify = btnSpinner.getText ().toString ();
                        intent.putExtra ("firstClassify", firstClassify); // 一级分类名
                        if (!TextUtils.isEmpty (firstClassify)) {
                            if (firstClassify.equals (getString (R.string.category_white_wine))) {  //白酒
                                intent.putExtra (CommonConst.IntentKey.BRAND_CODE, getString (R.string.category_wine_code));  //一级分类码
                            } else if (firstClassify.equals (getString (R.string.category_red_wine))) {  // 葡萄酒
                                intent.putExtra (CommonConst.IntentKey.BRAND_CODE, getString (R.string.category_red_wine_code)); //一级分类码
                            } else if (firstClassify.equals (getString (R.string.category_drinks))) {  // 饮料
                                intent.putExtra (CommonConst.IntentKey.BRAND_CODE, getString (R.string.category_code_drinks)); //一级分类码
                            } else if (firstClassify.equals (getString (R.string.category_non_staple))) { // 副食
                                intent.putExtra (CommonConst.IntentKey.BRAND_CODE, getString (R.string.category_code_non_staple)); //一级分类码
                            }
                            intent.putExtra ("secondaryIndex", -1);   //默认选择全部二级分类
                        }
                    }
                    //跳转到筛选画面
                    CategoryActivity.this.startActivityForResult (intent, 0);
                    break;

                default:
                    break;
            }
        }
    }

    /**
     * @param tupleProperty
     *         属性缓存
     * @param indexs
     *         二级分类下标
     * @param fromTag
     *         源点击标识（CategoryHolder--点击首页“分类“，二级分类进入；SelectTypeHeader，首页点击进入
     */
    private void setMerchCategoryCode (CommonUtils.CachingArrayList tupleProperty, Int2 indexs, String fromTag) {
        goodsform.setMerchCategoryCode (btnSpinner.getGoodsform ().getMerchCategoryCode ()); // 老品类设置品类码
        String classifyName = btnSpinner.getText ().toString ();
        // 如果是新增品类
        if (classifyName.equals (getString (R.string.category_non_staple))
                || classifyName.equals (getString (R.string.category_drinks)) || classifyName.equals (getString (R.string.category_grain))
                || classifyName.equals (getString (R.string.category_hardware)) || classifyName.equals (getString (R.string.category_daily_used))
                || classifyName.equals (getString (R.string.category_others))) {
            if (tupleProperty != null) {
                goodsform.setMerchCategoryCode (tupleProperty.get (0).getSecondValue ()); // 二级分类码
            } else if (indexs.y != -1 && !TextUtils.isEmpty (fromTag) && fromTag.equals ("CategoryHolder")) {
                if (null == agent.getCategory (indexs.x, indexs.y)) return;
                String categoryCode = agent.getCategory (indexs.x, indexs.y).getCode ();
                goodsform.setMerchCategoryCode (categoryCode);
            }
        }
    }

    /**
     * 设置请求商品列表的商品属性
     *
     * @param tupleProperty
     */
    private void setMerchPropertyValueCodeList (CommonUtils.CachingArrayList tupleProperty) {
        if (tupleProperty != null) {
            String classifyName = btnSpinner.getText ().toString ();
            // 如果是旧的分类
            if (!classifyName.equals (getString (R.string.classify)) && !classifyName.equals (getString (R.string.category_non_staple))
                    && !classifyName.equals (getString (R.string.category_drinks)) && !classifyName.equals (getString (R.string.category_grain))
                    && !classifyName.equals (getString (R.string.category_hardware)) && !classifyName.equals (getString (R.string.category_daily_used))
                    && !classifyName.equals (getString (R.string.category_others))) {
                List<String> merchPropertyValueCodeList = new ArrayList<> ();
                for (int i = 0; i < tupleProperty.size (); i++) {
                    merchPropertyValueCodeList.add (tupleProperty.get (i).getSecondValue ());
                }
                goodsform.setMerchPropertyValueCodeList (merchPropertyValueCodeList);
            }
        }
    }

    /**
     * 设置请求商品列表的商品名
     *
     * @param merchName
     *         商品名
     */
    private void setMerchName (String merchName) {
        if (!merchName.equals (getString (R.string.good_info_search_btnok))) {
            goodsform.setMerchName (merchName);
            goodsform.setMerchBrandId (null);
        }
    }

    /**
     * 设置请求商品列表的品牌码
     *
     * @param tupleBrand
     *         品牌名和品牌码的缓存体
     * @param indexs
     *         二级分类下标indexs.y 为 -1 表示选择了分类，并点击了“全部xxx商品”
     * @param fromTag
     *         源点击标识（CategoryHolder--点击首页“分类“，二级分类进入；SelectTypeHeader，首页点击进入
     */
    private void setBrandId (Tuple<String, String> tupleBrand, Int2 indexs, String fromTag) {
        String classifyName = btnSpinner.getText ().toString ();
        if (tupleBrand != null) {
            String brandId = tupleBrand.getFirstValue (); // 获取品牌码
            goodsform.setMerchBrandId (brandId);
        } else if (indexs.y != -1 && !TextUtils.isEmpty (fromTag) && fromTag.equals ("CategoryHolder")) { // 点击首页“分类“，二级分类进入
            if (agent.getCategory (indexs.x, indexs.y) == null) {
                return;
            }
            // 如果是旧分类
            if (!(classifyName.equals (getString (R.string.category_non_staple))
                    || classifyName.equals (getString (R.string.category_drinks)) || classifyName.equals (getString (R.string.category_grain))
                    || classifyName.equals (getString (R.string.category_hardware)) || classifyName.equals (getString (R.string.category_daily_used))
                    || classifyName.equals (getString (R.string.category_others)))) {
                String brandId = agent.getCategory (indexs.x, indexs.y).getCode ();
                goodsform.setMerchBrandId (brandId);
            }
        }
    }

    /**
     * 设置请求商品列表的 价格区间
     *
     * @param tuplePrice
     *         价格范围字符串
     */
    private void setPriceInterval (String tuplePrice) {
        if (!TextUtils.isEmpty (tuplePrice)) {
            // 如果价格缓存包括中文，1.xxx以上  2.全部
            if (CommonUtils.isContainChinese (tuplePrice)) {
                String lowPrice = CommonUtils.filterNumber (tuplePrice);
                String lowPriceFen = null;
                if (!TextUtils.isEmpty(lowPrice)) {
                    long pLow = Long.parseLong (lowPrice);
                    lowPriceFen = CommonUtils.yuanToFen (BigDecimal.valueOf (pLow)).toString ();
                } else {
                    // 选择“全部”价格,最低价设为“0”
                    long pLow = Long.parseLong ("0");
                    lowPriceFen = CommonUtils.yuanToFen (BigDecimal.valueOf (pLow)).toString ();
                }
                goodsform.setLowPrice (lowPriceFen);
            } else {
                String[] priceTemp = tuplePrice.split ("-");
                long pLow = Long.parseLong (priceTemp[0]);
                String lowPrice = CommonUtils.yuanToFen (BigDecimal.valueOf (pLow)).toString ();
                goodsform.setLowPrice (lowPrice); // 设置请求价格区间
                long pHight = Long.parseLong (priceTemp[1]);
                String hightPrice = CommonUtils.yuanToFen (BigDecimal.valueOf (pHight)).toString ();
                goodsform.setHighPrice (hightPrice); // 设置请求价格区间
            }
        }
    }
}